//
//  CQOauthViewController.swift
//  swift-weibo
//
//  Created by 陈乾 on 15/10/28.
//  Copyright © 2015年 陈乾. All rights reserved.
//

import UIKit
import SVProgressHUD

class CQOauthViewController: UIViewController {
    
    //MARK: -在loadView中拦截控制器的view赋值成我们的webview 好处：不要设置frame 系统帮忙设置好。
    override func loadView()
    {
        
        view = webView
        //设置代理
        webView.delegate = self
    }
    //MARK: viewDidLoad
    override func viewDidLoad()
    {
        super.viewDidLoad()
        //导航条左边添加返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        self.title = "T-mac微博"
        //通过单例获得url
        let request = NSURLRequest(URL: CQNetworkTool.shareInstance.getOauthUrl())
        //网络请求
        webView.loadRequest(request)
        
    }
    
    //MARK: -导航条左按钮点击
    func dismiss() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载webView
    lazy var webView :UIWebView = {
        
        let wb = UIWebView()
        return wb
        }()
    
    
    
}

extension CQOauthViewController: UIWebViewDelegate {
    
    
    //MARK: - 三个webView的代理方法
    /**
    当已经开始加载webView调用
    */
    func webViewDidStartLoad(webView: UIWebView) {
        //特点你不移除就一直在
        SVProgressHUD.showWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Gradient)
    }
    /**
    完成了记载调用这个
    */
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    /**
    加载之前调用 询问是否request正确
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        
        //获得绝对路径
        let  urlString = request.URL!.absoluteString
//        print("urlString:\(urlString)")
        
        //如果不是一百度开头 就返回true 可以加载
        if !urlString.hasPrefix(CQNetworkTool.shareInstance.redirect_uri)
        {
            
            return true
            
        }
        
        // http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // http://www.baidu.com/?code=8b56fa06bebf7dc058696c2b2897767e
        
        //如果上面的两个除去 baidu前缀 如果是code= 开头 就把code后面街区出来
        if let query = request.URL?.query
        {
            
            let codeStr = "code="
            //如果是以code=开头就截取后面的
            if query.hasPrefix(codeStr)
            {
                //转化成NSString
                
                let  qStr = query as NSString
                //截取完毕
                let code = qStr.substringFromIndex(codeStr.characters.count)
                
                //调用自己的函数 把code 传递过去 让他再去调用工具类的请求AccessToken的函数
                loadAccessToken(code)
            }else
            {
                
                //取消
            }
            
            
        }
        return false
        
    }
    //MARK: - 
    func warning(message: String) {
    
        //提醒
        SVProgressHUD.showErrorWithStatus(message, maskType: SVProgressHUDMaskType.Black)
        //延迟 1秒 关闭控制器
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            //关闭
            self.dismiss()
        });

    
    }
    
    //MARK: - 私有的loadAccessToken
    func loadAccessToken(code: String)
    {
        
        CQNetworkTool.shareInstance.loadAccessToken(code) { (result, error) -> () in
            //判断
            //有错误 结果为空的情况
            if error != nil || result == nil
            {
              
                self.warning("网络不给力..")
                //不让往下走了
                return
            }
            //来这说明 是拿到了result的
            //肯定是有值的就可以拆包
            //获得用户的accessToken uid 等。。
          let account = CQUserAccount(dic: result!)
//            print("********************\(result)")
            //保存到沙盒
            
            account.save()
            //加载用户头像 昵称
            account.loadUserInfo({ (error) -> () in
                //有错误
                if error != nil {
                self.warning("你长的太丑,数据不愿意来")
                    return
                }
                else{
                    //关闭退出
                 self.dismiss()
                 //切到welcomeVC
                (UIApplication.sharedApplication().delegate as! AppDelegate).switchVC(false)
                }
                
                
            })
            
           
        }
    
    
        
/*************End*************/
}
    
    
    
    
    
}

